var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

let initData = [];
table.render({
    elem: '#offer'
    ,data:initData
    ,url:"exportContract/getImportOfferByPage"
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'billNo', title:'报价单号',sort:true}
        ,{field:'customerName', title:'客户名称',sort:true}
        ,{field:'signingCompanyName', title:'签约单位',sort:true}
        ,{field:'createDate', title:'创建日期',sort:true}
        ,{field:'time', title:'报价日期',sort:true}
    ]]
    ,id: 'offertableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#offerproduct'
            ,url:"exportContract/getImportOfferDetail"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'productCode', title:'产品编码', sort : true}
                ,{field:'specificationCode', title:'规格编码', sort : true}
                ,{field:'specificationExplanation', title:'规格说明', sort : true}
                ,{field:'productCname', title:'中文名称', sort : true}
                ,{field:'productEname', title:'英文名称', sort : true}
                ,{field:'productNum', title:'数量', sort : true}
                ,{field:'remainingQuantity', title:'剩余数量', sort : true}
                ,{field:'productUnitName', title:'单位', sort : true}
                ,{field:'nameCustomsDeclaration',width: 120,title : '报关品名',sort : true}
                ,{field:'englishProductName',width: 120,title : '英文品名',sort : true}
                ,{field:'customsDeclarationUnit', title:'报关单位', sort : true}
            ]]
            ,id: 'offerproducttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].id
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });

    }
});

//监听主表复选框
table.on('checkbox(offertable)', function (data) {
    let id = data.data.id;
    table.reload('offerproducttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        done: function (res, curr, count) {
            let child = $("#offerproduct").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');

            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

function deleteData(data){
    let id = data.id;
    let parentId = data.parentId;
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j].id == id && changeList[j].parentId == parentId) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}

//监听子复选框
table.on('checkbox(offerproducttable)', function (obj) {
    if (obj.checked) {
        changeList.push(obj.data);
    } else {
        for (let index in changeList) {
            if (changeList[index].id == obj.data.id && changeList[index].parentId == obj.data.parentId) {
                changeList.splice(index,1);
            }
        }
    }
    form.render('checkbox');
});


//单击行事件
table.on('row(offertable)', function (obj) {
    let id = obj.data.id;
    table.reload('offerproducttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].id == res.data[i].id &&  changeList[j].parentId == res.data[i].parentId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');

});


form.on('submit(submitform)', function(data){
    table.reload('offertableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

//是否合作客户
function checkCustomerType(){
    let billNo = "";
    for(let i in changeList){
        let partner = changeList[i].offerInfo.partner;
        if(!partner){
            billNo = changeList[i].offerBillNo;
            break;
        }
    }
    return billNo;
}

$("#choose").on("click",function () {

    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        //判断是否存在合作客户
        let billNo = checkCustomerType();
        if(!isEmpty(billNo)){
            layer.msg("报价单号:" + billNo + ",客户类型为潜在类型，请调整客户类型。");
            return false;
        }
        //产品明细数据
        let oldData =  parent.table.cache["storageproductstableid"];
        //费用数据
        let oldCostData = parent.table.cache["costtableid"];
        //附件数据
        let oldAnnexData = parent.table.cache["attachmenttableid"];
        let tempCost = [];
        let tempAnnex = [];
        //交货日期
        let deliveryDate = parent.$("#carryTime").val();
        if(isEmpty(deliveryDate)){
            deliveryDate = currentDate;
        }
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i]["sameId"] != "undefined" && oldData[i]["sameId"] == changeList[index].id;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //不存在重复数据,添加数据
                //1.产品
                let tempData = changeList[index];
                tempData["tempId"] = GenNonDuplicateID(3) + (index+1)
                tempData["sameId"] = tempData.id;
                tempData["deliveryDate"] = deliveryDate;
                tempData["id"] = null;
                oldData.push(tempData);

                //2.费用
                let costList = tempData.costList;
                for(let i in costList){
                    tempCost.push(costList[i]);
                }

                //3.附件
                let annexList = tempData.annexList;
                for(let i in annexList){
                    tempAnnex.push(annexList[i]);
                }
            }

        });

        //剔除重复费用
        let newCostData = deleteObject(tempCost);
        let newTempCost = [];
        for(let i in newCostData){
            let flag = true;
            for(let j in oldCostData){
                if(newCostData[i].id == oldCostData[j].tempId){
                    flag = false;
                    break;
                }
            }
            if(flag){
                //不存在重复费用数据,新增
                newCostData[i]["tempId"] = newCostData[i].id;
                newCostData[i].id = null;
                newTempCost.push(newCostData[i]);
            }
        }
        oldCostData.push.apply(oldCostData, newTempCost);

        //剔除重复附件
        let newAnnexData = deleteObject(tempAnnex);
        let newTempAnnex = [];
        for(let i in newAnnexData){
            let flag = true;
            for(let j in oldAnnexData){
                if(newAnnexData[i].id == oldAnnexData[j].id){
                    flag = false;
                    break;
                }
            }
            if(flag){
                //不存在重复附件数据,新增
                newTempAnnex.push(newAnnexData[i]);
            }
        }
        oldAnnexData.push.apply(oldAnnexData, newTempAnnex);

        //重载产品明细表单
        parent.table.reload('storageproductstableid', {data:oldData, limit:oldData.length});

        //重载费用明细表单
        parent.table.reload('costtableid', {data:oldCostData, limit:oldCostData.length});

        //重载附件表单
        parent.table.reload('attachmenttableid', {data:oldAnnexData, limit:oldAnnexData.length});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})


$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}
//删除数组对象中重复对象
function deleteObject(obj) {
    let uniques = [];
    let stringify = {};
    for (let i = 0; i < obj.length; i++) {
        let keys = Object.keys(obj[i]);
        keys.sort(function(a, b) {
            return (Number(a) - Number(b));
        });
        let str = '';
        for (let j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
        }
    }
    uniques = uniques;
    return uniques;
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

let currentDate = getNowFormatDate(1);